import {getRequest} from "./api";

export const initMenu = (router,store) => {
    //判断vuex中有没有数据
    if(store.state.routes.length>0){
        return;
    }
    //没有数据则执行下面获取并存储数据
    getRequest('/menu').then(data=>{
        if (data){
            //格式化Router
            let fmtRoutes = formatRoutes(data);
            //添加到router
            router.addRoutes(fmtRoutes);
            //将数据存入vuex
            store.commit('initRoutes',fmtRoutes);
        }
    })
}

export const formatRoutes = (routes) => {
    let fmtRoutes = [];
    routes.forEach(router => {
        let {
            path,
            component,
            name,
            iconCls,
            children
        } = router;
        if (children && children instanceof Array) {
            //递归
            children = formatRoutes(children);
        }
        let fmRouter = {
            path: path,
            name: name,
            iconCls: iconCls,
            children: children,
            component(resolve){
                //ES5写法
                if (component.startsWith('Home')) {
                    require(['../views/' + component + '.vue'], resolve);
                }else if (component.startsWith('Good')){
                    require(['../views/good/'+component+'.vue'],resolve);
                }else if (component.startsWith('User')){
                    require(['../views/user/'+component+'.vue'],resolve);
                }else if (component.startsWith('Order')){
                    require(['../views/order/'+component+'.vue'],resolve);
                }else if (component.startsWith('Sys')){
                    require(['../views/sys/'+component+'.vue'],resolve);
                }
            }
        }
        fmtRoutes.push(fmRouter);
    });
    return fmtRoutes;
}

